﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Alert_Form.Component.Alert;
using YXChatFormClient.Dtos;
using YXChatFormClient.Dtos.Buddy;
using YXChatFormClient.Dtos.ChatRecord;
using YXChatFormClient.Global;
using YXChatFormClient.Utility;
using YXChatFormClient.Utility.HubHelp;

namespace YXChatFormClient.UserControls
{
    public partial class UC_MessageContainer : UserControl
    {
        /// <summary>
        /// 正在聊天的好友的聊天记录
        /// </summary>
        public ChatRecordAccountDto ChatRecordAccountDto { get; set; }
        public UC_MessageContainer()
        {
            InitializeComponent();
            //设置控件样式
            SetStyle(
                    ControlStyles.AllPaintingInWmPaint | //不闪烁
                    ControlStyles.OptimizedDoubleBuffer //支持双缓存
                   , true);
        }
        /// <summary>
        /// 当前消息气泡起始位置
        /// </summary>
        private int _top = 0;

        /// <summary>
        /// 当前消息气泡高度
        /// </summary>
        private int _height = 0;

        /// <summary>
        /// 显示接收消息
        /// </summary>
        /// <param name="content"></param>
        private void ShowReceiveMessage(string content)
        {
            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Receive,
                BuddyAvatar = ChatRecordAccountDto.Account.Avatar
            };
            item.SetWeChatContent(content);

            //计算高度
            item.Top = _top + _height;
            item.Left = 15;

            _top = item.Top;
            _height = item.HEIGHT;

            //滚动条移动最上方，重新计算气泡在panel的位置
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);
        }

        /// <summary>
        /// 更新界面，显示发送消息
        /// </summary>
        private async void AddSendMessage(string content)
        {
            #region 发送消息持久化
            CreateChatRecordInput input = new CreateChatRecordInput
            {
                SNumber = GlobalAccountInfo.Account.AccountNumber,
                RNumber = ChatRecordAccountDto.Account.AccountNumber,
                Content = content,
                CreateTime = DateTime.Now
            };
            HttpHelper http = new HttpHelper();
            await http.PostAsync<object>(Api.CreateChatRecord, input);
            #endregion

            #region 追加气泡

            UC_MsgItem item = new UC_MsgItem { messageType = UC_MsgItem.MessageType.Send };
            item.SetWeChatContent(content);

            item.Top = _top + _height;
            item.Left = this.Width - 65 - item.WIDTH;

            _top = item.Top;
            _height = item.HEIGHT;
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);

            #endregion

            var panelMenuItems = ParentForm.Controls.Find("panelMenuItems", true)[0];
            var chatContainer = panelMenuItems.Controls[0];
            foreach (Control control in chatContainer.Controls)
            {
                if (control is UC_ChatItem chatItem)
                {
                    // 如果当前接收的消息的发送者 = 当前聊天窗口的好友 
                    if (chatItem.ChatRecordAccount.Account.AccountNumber == input.RNumber)
                    {
                        // 判断是新增加的聊天 因为新增加的聊天item中没有聊天记录
                        if (chatItem.ChatRecordAccount.ChatRecord.Any())
                        {
                            chatItem.ChatRecordAccount.ChatRecord[0].Content = input.Content;
                            chatItem.ChatRecordAccount.ChatRecord[0].CreateTime = input.CreateTime;
                        }
                        else
                        {
                            chatItem.ChatRecordAccount.ChatRecord.Add(new ChatRecordDto()
                            {
                                SNumber = GlobalAccountInfo.Account.AccountNumber,
                                RNumber = input.RNumber,
                                Content = input.Content,
                                CreateTime = input.CreateTime
                            });
                        }
                        chatItem.Refresh();
                    }
                }
            }
        }
        /// <summary>
        /// 更新界面，初始化显示发送消息
        /// </summary>
        private void ShowSendMessage(string content)
        {
            UC_MsgItem item = new UC_MsgItem { messageType = UC_MsgItem.MessageType.Send };
            item.SetWeChatContent(content);

            item.Top = _top + _height;
            item.Left = this.Width - 65 - item.WIDTH;

            _top = item.Top;
            _height = item.HEIGHT;
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);
        }

        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            AddSendMessage(tbMsg.Text);
            panelMessage.AutoScrollPosition = new Point(0, this._top);
            tbMsg.Clear();
        }

        private void panelMessageInput_Paint(object sender, PaintEventArgs e)
        {
            PaintHelper.PaintBorder(e, panelMessage.ClientRectangle, Color.White,
                Color.FromArgb(214, 214, 214), Color.White, Color.White);
        }

        private void UC_MessageContainer_Load(object sender, EventArgs e)
        {
            ChatService.Connection.Remove("SendMessage");
            ChatService.ReceiveSendMessage(ReceiveSendMessageHandler);
            ChatRecordAccountDto.ChatRecord.Reverse();
            var selfNumber = GlobalAccountInfo.Account.AccountNumber;
            foreach (var item in ChatRecordAccountDto.ChatRecord)
            {
                if (item.SNumber.Equals(selfNumber))
                {
                    ShowSendMessage(item.Content);
                }
                else
                {
                    ShowReceiveMessage(item.Content);
                }
            }
        }
        #region chat
        protected void ReceiveSendMessageHandler(MessageNotifyDto messageNotify)
        {
            Invoke((MethodInvoker)delegate ()
            {
                // 1.Alert提示有新消息
                AlertForm.ShowAlert($"{messageNotify.Account.NickName} 给您发了一条信息",
                    AlertType.Info, 3,
                    direction: ShowDirection.BottomRight);
                // 2，如果当前接收的消息的发送者 = 当前聊天窗口的好友 则追加气泡
                if (messageNotify.Account.AccountNumber.Equals(ChatRecordAccountDto.Account.AccountNumber))
                {
                    ShowReceiveMessage(messageNotify.ChatRecordDto.Content);
                }
                // 3.修改聊天列表的最后一条消息和显示时间
                if (ParentForm != null)
                {
                    var menuItems = ParentForm.Controls.Find("panelMenuItems", true)[0];
                    var chatContainer = menuItems.Controls[0] as UC_ChatsContainer;
                    List<UC_ChatItem> chats = new List<UC_ChatItem>();
                    if (chatContainer != null)
                    {
                        // 找出所有聊天item控件
                        foreach (Control control in chatContainer.Controls)
                        {
                            if (control is UC_ChatItem chatItem)
                            {
                                chats.Add(chatItem);
                            }
                        }

                        // 如果接收到的消息的发送者在聊天列表中已经存在 则true
                        var receiveChatItem = chats.FirstOrDefault(n =>
                            n.ChatRecordAccount.Account.AccountNumber == messageNotify.Account.AccountNumber);
                        // 存在 则修改数据
                        if (receiveChatItem != null)
                        {
                            receiveChatItem.ChatRecordAccount.ChatRecord[0] = messageNotify.ChatRecordDto;
                            receiveChatItem.Refresh();
                        }
                        // 不存在 则添加聊天item控件
                        else
                        {
                            UC_ChatItem chatItem = new UC_ChatItem()
                            {
                                Dock = DockStyle.Top,
                                ChatRecordAccount = new ChatRecordAccountDto()
                                {
                                    Account = messageNotify.Account,
                                    ChatRecord = new List<ChatRecordDto>()
                                    {
                                        messageNotify.ChatRecordDto
                                    }
                                }
                            };
                            chatItem.ChatClick += chatContainer.ChatItem_ChatClick;
                            chatContainer.Controls.Add(chatItem);

                            // 重新渲染聊天menu容器
                            menuItems.Controls.Clear();
                            menuItems.Controls.Add(chatContainer);
                        }
                    }
                }
            });                
        }
        #endregion
    }
}
